import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Tabs, Popconfirm, Spin } from 'antd';
import { ModalC, SelectC, SingleDateC, InputNumberC, InputC } from '../../../../comps';
import style from '../index.less';
import moment from 'moment';

const { TabPane } = Tabs;
@Form.create()
class SceneModal extends PureComponent {
  state = {
    sceneNameList: [],
    sceneTypeList: [
      {
        value: '1',
        title: '历史情景',
      },
      {
        value: '2',
        title: '压力情景',
      },
    ], // 情景类型
    pressureRangeList: [
      {
        value: '3M',
        title: '3M',
      },
      {
        value: '6M',
        title: '6M',
      },
      {
        value: '9M',
        title: '9M',
      },
      {
        value: '1Y',
        title: '1Y',
      },
    ], // 压力区间
    directionList: [
      {
        value: '1',
        title: '上涨',
      },
      {
        value: '2',
        title: '下跌',
      },
    ], // 标的变动方向
    sceneTypeAdd: 1, // 新增列表情景类型切换
    sceneTypeEdit: 1, // 查询列表情景类型切换
    tabCurrent: 1,
    // 查询时选择的情景名称
    selectId: '',
    selectName: '',
    // 历史情景
    beginDate: '',
    endDate: '',
    pressure: '',
    // 压力情景
    changeRange: '',
    direction: '',
    pressureRange: '',
    selectBeginData: '', // 选择起始日
    selectEndData: '', // 选择终止日
  };

  componentDidMount() {}

  resetData = () => {
    this.setState({
      selectId: '',
      selectName: '',
      beginDate: '',
      endDate: '',
      pressure: '',
      changeRange: '',
      direction: '',
      pressureRange: '',
      selectBeginData: '',
      selectEndData: '',
      sceneTypeEdit: 1,
    });
  };

  // tab切换
  tabChange = (e) => {
    const {
      form: { resetFields },
    } = this.props;
    resetFields();
    this.resetData();
    this.setState({
      tabCurrent: e,
    });
  };

  // 情景类型切换
  sceneTypeChange = (e) => {
    const {
      form: { resetFields },
    } = this.props;
    resetFields();
    if (this.state.tabCurrent == 1) {
      this.setState({
        sceneTypeAdd: e,
      });
    } else {
      this.setState({
        sceneTypeEdit: e,
      });
    }
  };

  // 查询列表搜索情景名称
  sceneNameChange = (e) => {
    const temp = this.props.sceneNameList.filter((item) => {
      return item.sceneId === e;
    });
    this.setState({
      selectId: temp[0].id,
      selectName: temp[0].sceneName,
      // 历史情景
      beginDate: temp[0].beginDate,
      endDate: temp[0].endDate,
      pressure: temp[0].pressure,
      // 压力情景
      changeRange: temp[0].changeRange,
      direction: temp[0].direction,
      pressureRange: temp[0].pressureRange,
    });
  };

  // 新增表单
  addForm = () => {
    const { sceneTypeList, sceneTypeAdd, pressureRangeList, directionList, selectBeginData, selectEndData } = this.state;
    return (
      <Row>
        <Col>
          <SelectC
            dataIndex='sceneType0'
            form={this.props.form}
            title='情景类型'
            initialValue={sceneTypeList[0].title}
            rules={[{ required: true, message: '情景类型不能为空!' }]}
            multiple={false}
            dataSource={sceneTypeList ? sceneTypeList : []}
            onChange={this.sceneTypeChange}
          />
        </Col>
        <Col>
          <InputC title='情景名称' form={this.props.form} dataIndex='sceneName0' placeholder='请输入' max={20} rules={[{ required: true, message: '情景名称不能为空!' }]} />
        </Col>
        {sceneTypeAdd == 1 ? (
          <>
            <Col>
              <SingleDateC
                form={this.props.form}
                title='起始日'
                rules={[{ required: true, message: '请输入起始时间' }]}
                dataIndex='beginDate0'
                disableEnd={selectEndData || moment()}
                onChange={(e) => this.setState({ selectBeginData: e ? moment(e).add(-1, 'days') : '' })}
              />
            </Col>
            <Col>
              <SingleDateC
                form={this.props.form}
                title='终止日'
                rules={[{ required: true, message: '请输入终止时间' }]}
                dataIndex='endDate0'
                disableBegin={selectBeginData}
                disableEnd={moment()}
                onChange={(e) => this.setState({ selectEndData: e ? moment(e).add(1, 'days') : '' })}
              />
            </Col>
            <Col>
              <InputNumberC
                form={this.props.form}
                dataIndex='pressure0'
                splitStyle={true}
                min={0.01}
                precision={2}
                rules={[{ pattern: /^(0\.0*[1-9]+[0-9]*$|[1-9]+[0-9]*\.[0-9]*[0-9]$|[1-9]+[0-9]*$)/, message: '压力系数必须大于0' }]}
                title='压力系数'
              />
            </Col>
          </>
        ) : (
          <>
            <Col>
              <SelectC
                dataIndex='pressureRange0'
                form={this.props.form}
                title='压力区间'
                rules={[{ required: true, message: '压力区间不能为空!' }]}
                multiple={false}
                filterOption={false}
                dataSource={pressureRangeList}
              />
            </Col>
            <Col>
              <SelectC
                dataIndex='direction0'
                form={this.props.form}
                title='标的变动方向'
                rules={[{ required: true, message: '变动方向不能为空!' }]}
                multiple={false}
                filterOption={false}
                dataSource={directionList}
              />
            </Col>
            <Col>
              <InputNumberC
                form={this.props.form}
                dataIndex='changeRange0'
                min={0.01}
                rules={[
                  { required: true, message: '涨跌幅不能为空!' },
                  { pattern: /^(0\.0*[1-9]+[0-9]*$|[1-9]+[0-9]*\.[0-9]*[0-9]$|[1-9]+[0-9]*$)/, message: '涨跌幅必须大于0' },
                ]}
                precision={2}
                splitStyle={true}
                title='涨跌幅'
                unit='%'
              />
            </Col>
          </>
        )}
      </Row>
    );
  };

  // 查询表单
  editForm = () => {
    const { sceneNameList } = this.props;
    const {
      sceneTypeList,
      sceneTypeEdit,
      pressureRangeList,
      directionList,
      beginDate,
      endDate,
      pressure,
      changeRange,
      direction,
      pressureRange,
      selectId,
      selectBeginData,
      selectEndData,
    } = this.state;

    return (
      <div>
        <Row>
          <Col>
            <SelectC
              dataIndex='sceneType1'
              form={this.props.form}
              title='情景类型'
              initialValue={sceneTypeList[0].title}
              rules={[{ required: true, message: '情景类型不能为空!' }]}
              multiple={false}
              dataSource={sceneTypeList}
              onChange={this.sceneTypeChange}
            />
          </Col>
          <Col>
            <SelectC
              dataIndex='sceneName1'
              form={this.props.form}
              title='情景名称'
              rules={[{ required: true, message: '情景名称不能为空!' }]}
              multiple={false}
              dataSource={this.listData(sceneNameList)}
              allowClear={true}
              showSearch={true}
              onChange={this.sceneNameChange}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            />
            {!selectId ? null : (
              <div className={style.deleteBtn}>
                <Popconfirm
                  title='确定删除？'
                  icon={<QuestionCircleOutlined />}
                  onConfirm={(e) => {
                    this.onDeleteGroup();
                  }}
                >
                  <a>删除</a>
                </Popconfirm>
              </div>
            )}
          </Col>
          {sceneTypeEdit == 1 ? (
            <>
              <Col>
                <SingleDateC
                  form={this.props.form}
                  title='起始日'
                  rules={[{ required: true, message: '请输入起始时间' }]}
                  dataIndex='beginDate1'
                  initialValue={beginDate ? moment(beginDate) : null}
                  disableEnd={selectEndData || moment()}
                  onChange={(e) => this.setState({ selectBeginData: e ? moment(e).add(-1, 'days') : '' })}
                />
              </Col>
              <Col>
                <SingleDateC
                  form={this.props.form}
                  title='终止日'
                  initialValue={endDate ? moment(endDate) : null}
                  rules={[{ required: true, message: '请输入终止时间' }]}
                  dataIndex='endDate1'
                  disableBegin={selectBeginData}
                  disableEnd={moment()}
                  onChange={(e) => this.setState({ selectEndData: e ? moment(e).add(1, 'days') : '' })}
                />
              </Col>
              <Col>
                <InputNumberC
                  form={this.props.form}
                  dataIndex='pressure0'
                  splitStyle={true}
                  min={0.01}
                  precision={2}
                  rules={[{ pattern: /^(0\.0*[1-9]+[0-9]*$|[1-9]+[0-9]*\.[0-9]*[0-9]$|[1-9]+[0-9]*$)/, message: '压力系数必须大于0' }]}
                  title='压力系数'
                  initialValue={pressure}
                />
              </Col>
            </>
          ) : (
            <>
              <Col>
                <SelectC
                  dataIndex='pressureRange1'
                  form={this.props.form}
                  title='压力区间'
                  initialValue={pressureRange}
                  rules={[{ required: true, message: '压力区间不能为空!' }]}
                  multiple={false}
                  filterOption={false}
                  dataSource={pressureRangeList}
                />
              </Col>
              <Col>
                <SelectC
                  dataIndex='direction1'
                  form={this.props.form}
                  title='标的变动方向'
                  initialValue={direction}
                  rules={[{ required: true, message: '变动方向不能为空!' }]}
                  multiple={false}
                  filterOption={false}
                  dataSource={directionList}
                />
              </Col>
              <Col>
                <InputNumberC
                  form={this.props.form}
                  dataIndex='changeRange1'
                  min={0.01}
                  initialValue={changeRange}
                  precision={2}
                  splitStyle={true}
                  rules={[
                    { required: true, message: '涨跌幅不能为空!' },
                    { pattern: /^(0\.0*[1-9]+[0-9]*$|[1-9]+[0-9]*\.[0-9]*[0-9]$|[1-9]+[0-9]*$)/, message: '涨跌幅必须大于0' },
                  ]}
                  title='涨跌幅'
                  unit='%'
                />
              </Col>
            </>
          )}
        </Row>
      </div>
    );
  };

  // 情景名称列表筛选
  listData = (arr) => {
    const { sceneTypeEdit } = this.state;
    const list = [];
    arr.map((item) => {
      if (item.sceneType == sceneTypeEdit) {
        (item.title = item.sceneName), (item.value = item.sceneId), list.push(item);
      }
    });
    return list;
  };

  // 删除情景设置
  onDeleteGroup = () => {
    this.props.dispatch({
      type: 'pressureTestM/deleteScene',
      payload: {
        id: this.state.selectId,
      },
      callback: (res) => {
        this.resetData();
        message.success('删除成功');
        this.props.form.resetFields();
        this.props.getSceneNameList();
      },
    });
  };

  render() {
    const {
      form: { validateFields, resetFields },
      dispatch,
      visibleModal,
      loading,
    } = this.props;
    const { tabCurrent, selectId, sceneTypeAdd, sceneTypeEdit, selectName } = this.state;
    const modalProps = {
      visible: visibleModal,
      confirmLoading: loading.effects['pressureTestM/addScene'] === true || loading.effects['pressureTestM/editScene'] === true,
      onOk: () => {
        validateFields((err, values) => {
          if (!err) {
            const obj = {};
            const arr = Object.keys(values);
            for (let i = 0; i < arr.length; i++) {
              const element = arr[i].substr(0, arr[i].length - 1);
              if (element == 'beginDate' || element == 'endDate') {
                obj[element] = values[arr[i]].format('YYYY-MM-DD');
              } else {
                obj[element] = values[arr[i]];
              }
            }
            if (tabCurrent == 1) {
              obj.sceneType = sceneTypeAdd;
              dispatch({
                type: 'pressureTestM/addScene',
                payload: obj,
                callback: (res) => {
                  this.setState({
                    sceneTypeAdd: 1,
                    selectBeginData: '',
                    selectEndData: '',
                  });
                  message.success('添加成功');
                  resetFields();
                  this.props.getSceneNameList();
                },
              });
            } else {
              obj.sceneId = obj.sceneName;
              obj.id = selectId;
              obj.sceneName = selectName;
              obj.sceneType = sceneTypeEdit;
              dispatch({
                type: 'pressureTestM/editScene',
                payload: obj,
                callback: (res) => {
                  this.resetData();
                  message.success('编辑成功');
                  resetFields();
                  this.props.getSceneNameList();
                },
              });
            }
          }
        });
      },
      onCancel: () => {
        resetFields();
        this.setState({
          tabCurrent: 1,
          sceneTypeAdd: 1,
          sceneTypeEdit: 1,
        });
        this.props.openModal();
        this.resetData();
      },
      title: '情景设置',
      // className: style.sceneModal,
      height: 250, // 内容区域的高度
      width: 420,
      maskClosable: false, // 点击蒙层是否允许关闭
    };

    return (
      <div className={style.modalBox}>
        <ModalC {...modalProps}>
          <Spin spinning={loading.effects['pressureTestM/deleteScene'] == true}>
            <div className='secondTabContainer'>
              <Tabs activeKey={tabCurrent.toString()} onChange={this.tabChange}>
                <TabPane tab='新增' key='1'>
                  {tabCurrent == 1 ? this.addForm() : null}
                </TabPane>
                <TabPane tab='查询' key='2'>
                  {tabCurrent == 2 ? this.editForm() : null}
                </TabPane>
              </Tabs>
            </div>
          </Spin>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ pressureTestM, loading }) => ({ pressureTestM, loading }))(SceneModal);
